package me.xhy.java.springboot3.webflux.s01simplereactorhttpserver;

import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.http.server.reactive.HttpHandler;
import org.springframework.http.server.reactive.ReactorHttpHandlerAdapter;
import reactor.core.publisher.Mono;
import reactor.netty.http.server.HttpServer;

import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

public class S02ReactorHttpServer {

  public static void main(String[] args) throws Exception {

    // 1. 一个能处理 Http 请求的处理器
    HttpHandler httpHandler = (request, response) -> {
      // b 创建一个 DateBuffer
      DataBufferFactory dataBufferFactory = response.bufferFactory();
      DataBuffer dataBuffer = dataBufferFactory.wrap("Spring Flux".getBytes(StandardCharsets.UTF_8));

      // a 向客服端返回数据 需要一个 Publisher<DateBuffer>，需要返回 Mono.just(传入 DateBuffer)
      Mono<Void> voidMono = response.writeWith(Mono.just(dataBuffer));

      // c 结束本次响应， HttpHandler 返回的就是 Mono<Void> 类型
      return voidMono;
    };

    // 2. 启动服务器
    ReactorHttpHandlerAdapter adapter = new ReactorHttpHandlerAdapter(httpHandler);
    // 3. 启动Netty服务器
    HttpServer.create().host("0.0.0.0").port(8080).handle(adapter).bindNow();

    // 4. 测试，使用阻塞方法阻止主线程退出
    TimeUnit.SECONDS.sleep(10);
    
  }
}
